package com.ray.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.ray.log.WebLog;
import com.ray.model.File;
import com.ray.util.Ret;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    /**
     * @note 上传到临时文件夹
     * @time 2024年03月26日 15:16:24
     * @author Ray
     */
    @RequestMapping("upload")
    @WebLog(description = "上传到临时文件夹")
    public Ret upload(@RequestParam MultipartFile file, String column) throws IOException {
        if (file != null && !file.isEmpty()) {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(domin_path + "/temp", file.getOriginalFilename());
            Files.write(path, bytes);
            return Ret.ok("msg", "上传到临时文件夹成功").set("fileName", file.getOriginalFilename()).set("column", column);
        } else {
            return Ret.fail("上传到临时文件夹失败");
        }
    }

    /**
     * @note 确认上传
     * @time 2024年03月26日 15:38:10
     * @author Ray
     */
    @RequestMapping("confirmUpload")
    @WebLog(description = "确认上传")
    public Ret confirmUpload(@RequestBody JSONObject param) {
        JSONArray fileArray = param.getJSONArray("fileList");
        if (fileArray != null) {
            List<Record> respFileList = new ArrayList<Record>();
            String accpetTypes = param.getString("accpetTypes");
            for (int i = 0; i < fileArray.size(); i++) {
                JSONObject jb = fileArray.getJSONObject(i);
                if (!"".equals(jb.getString("response")) && jb.getString("response") != null) {
                    JSONObject response = jb.getJSONObject("response");
                    java.io.File file = new java.io.File(domin_path + "/temp/" + response.getString("fileName"));
                    String fileType = response.getString("fileName").split("\\.")[response.getString("fileName").split("\\.").length - 1];
                    if (!".*".equals(accpetTypes) && accpetTypes.toLowerCase().indexOf(fileType.toLowerCase()) == -1) {
                        return Ret.fail("msg", "新增失败，原因：附件不支持此文件类型-" + fileType);
                    }
                    java.io.File newfile = new java.io.File(domin_path + "/" + param.getString("folder") + "/" + UUID.randomUUID() + "." + fileType);
                    java.io.File fileParent = newfile.getParentFile();
                    //判断文件夹是否存在
                    if (!fileParent.exists()) {
                        fileParent.mkdirs();
                    }
                    //从temp文件夹移动到正式文件夹
                    if (file.renameTo(newfile)) {
                        Record fileRecord = new Record();
                        fileRecord.set("name", response.getString("fileName"));
                        fileRecord.set("url", "/" + param.getString("folder") + "/" + newfile.getName());
                        Db.use(base).save("file", fileRecord);
                        respFileList.add(fileRecord);
                    } else {
                        return Ret.fail("msg", "新增失败，原因：文件处理失败");
                    }
                }
            }
            return Ret.ok("msg", "成功").setJson("respFileList", respFileList);
        } else {
            return Ret.fail("msg", "请选择要上传的文件");
        }
    }

    /**
     * @note 获取文件列表
     * @time 2024年03月26日 15:24:04
     * @author Ray
     */
    @RequestMapping("getFileList")
    @WebLog(description = "获取文件列表")
    public Ret getFileList(String ids) {
        List<File> list = fileList(ids);
        return Ret.ok("msg", "成功").setJson("list", list);
    }

    public List<File> fileList(String ids) {
        List<File> list = new ArrayList<File>();
        if (ids != null && !"".equals(ids)) {
            list = File.dao.find("select *,CONCAT('" + domin_url + "',url) as url from file where id in (" + ids + ")");
        }
        return list;
    }
}
